package com.banmao.youZone.config;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.banmao.youZone.entity.UserVO;
import com.banmao.youZone.util.RequestUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;

import java.util.ArrayList;

@Slf4j
@ControllerAdvice(basePackages = "com.banmao.youZone.model")
public class ModelControllerAdvice {

    private static final String BUILD_TIME = DateUtil.date().toString(DatePattern.NORM_DATETIME_MINUTE_FORMAT);

    private static final ArrayList<String> NO_USER_SESSION = new ArrayList<String>() {
        {
            add("");
            add("\\");
            add("/");
            add("/index");
            add("/index/");
        }
    };

    @ModelAttribute
    public void handleModel(Model model) {
        model.addAttribute("buildTime", BUILD_TIME);

        String requestURI = RequestUtil.getRequest().getRequestURI();
        if (!NO_USER_SESSION.contains(requestURI)) {
            Object userVOObj = null;
            try {
                userVOObj = RequestUtil.getSessionUser();
            } catch (Exception e) {
                return;
            }
            if (userVOObj instanceof UserVO userVO) {
                model.addAttribute("userId", userVO.getUserId());
                model.addAttribute("userName", userVO.getUsername());
            }
        }

    }

    @ExceptionHandler(Exception.class)
    public String handleException(HttpServletRequest request, Exception ex, Model model) {
        log.error("[ModelHandleException]error:", ex);
        model.addAttribute("message", ex.getMessage() == null ?
                ex.getCause().getMessage() : ex.getMessage());
        return "/error";
    }

}
